﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Data;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain.ViewModel;

namespace YunSpace.Application.OrderFlowManage
{
    public class CheckOrderJobApp
    {
        public List<SelectListItemViewModel> GetItemList(string enCode)
        {
            var sqlStr = @"SELECT sid.F_ItemCode Value, sid.F_ItemName Text,sid.F_Description FROM Sys_Items si
	                            LEFT JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
	                            WHERE si.F_EnCode=@enCode order by sid.F_SortCode";

            var dbParams = new MySqlParameter[] {
                new MySqlParameter("@enCode", enCode)
            };
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<SelectListItemViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        public List<CheckOrderJobOutput> ExecuteCheckOrder(string Day)
        {
            string sqlStr = $@"SELECT 
	                            t.F_ActivityTheme,
	                            t3.F_RealName,t3.F_Account,t3.F_MobilePhone,
	                            t3.F_DepartmentId,
	                            TIMESTAMPDIFF(DAY,now(),t.F_CreatorTime) time
	                            FROM Site_Clients_ProjectByDemand t
	                            INNER JOIN Site_Client_Order t2 on t.F_Id=t2.F_DemandId
	                            INNER JOIN Sys_User t3 on t2.F_FlowUserId=t3.F_Id
	                            WHERE 
		                            TIMESTAMPDIFF(DAY,t.F_CreatorTime,now())>={Day} AND
	                             t2.F_OrderState<=1";

            using (var db = new RepositoryBase())
            {
                var list = db.FindList<CheckOrderJobOutput>(sqlStr);
                if (list != null && list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        var Department = item.F_DepartmentId;
                        var Organize = db.FindEntity<OrganizeEntity>(t => t.F_Id == Department);
                        var managerId = Organize.F_ManagerId.Split(',');
                        item.ManagerPhone = new List<string>();
                        foreach (var it in managerId)
                        {
                            var UserEntity = db.FindEntity<UserEntity>(t => it == t.F_Id);
                            if (UserEntity != null)
                                item.ManagerPhone.Add(UserEntity.F_MobilePhone);
                        }
                    }
                }
                return list;
            }
        }
    }
}
